//
//  UpdatePwdViewController.swift
//  koolcar
//
//  Created by xiantian on 2023/11/2.
//

import UIKit
import RxSwift

class UpdatePwdViewController: BaseViewController {
    var phoneStr: String = ""
    var captCode: String = ""
    
    var titleLab: UILabel!
    var oldPwdView: KInputTextField!
    var password1View: KInputTextField!
    var password2View: KInputTextField!
    var descLab: UILabel!
    var bottomBtn: UIButton!
    
    var disBag = DisposeBag()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navBar.wr_setBottomLineHidden(hidden: true)
        titleLab = UILabel()
        titleLab.textColor = Theme.mainColor
        titleLab.backgroundColor = UIColor.clear
        titleLab.font = UIFont.init(name: Theme.PingFangSCMedium, size: 26)
        titleLab.numberOfLines = 1
        titleLab.lineBreakMode = .byTruncatingTail
        titleLab.text = MMLocalizedString("reset_pwd", comment: "更改密码")
        view.addSubview(titleLab)
        
        //旧密码
        oldPwdView = KInputTextField.init(frame: .zero)
        oldPwdView.textField.isSecureTextEntry = true
        oldPwdView.textField.keyboardType = .namePhonePad
        oldPwdView.textField.returnKeyType = .done
        oldPwdView.placeholder = MMLocalizedString("update_input_old_password", comment: "请输入旧密码")
        self.view.addSubview(oldPwdView)
        
        //密码1
        password1View = KInputTextField.init(frame: .zero)
        password1View.textField.isSecureTextEntry = true
        password1View.textField.keyboardType = .namePhonePad
        password1View.textField.returnKeyType = .done
        password1View.placeholder = MMLocalizedString("reset_pwd_input", comment: "请输入新密码")
        self.view.addSubview(password1View)
        
        //密码2
        password2View = KInputTextField.init(frame: .zero)
        password2View.textField.isSecureTextEntry = true
        password2View.textField.keyboardType = .namePhonePad
        password2View.textField.returnKeyType = .done
        password2View.placeholder = MMLocalizedString("reset_pwd_input_again", comment: "请再次输入新密码")
        password2View.textField.isSecureTextEntry = true
        self.view.addSubview(password2View)
        
        //说明
        descLab = UILabel()
        descLab.textColor = Theme.placeholderColor
        descLab.backgroundColor = UIColor.clear
        descLab.font = UIFont.init(name: Theme.PingFangSCRegular, size: 12)
        descLab.numberOfLines = 0
        descLab.lineBreakMode = .byTruncatingTail
        descLab.textAlignment = .left
        descLab.text = MMLocalizedString("reset_pwd_rule", comment: "密码为8~13位数字+字母组合")
//        descLab.isHidden = true
        self.view.addSubview(descLab)
        
        //登录
        bottomBtn = UIButton()
        bottomBtn.setup_titleLabel(text: MMLocalizedString("reset_pwd_done", comment: "完成"))
        bottomBtn.setup_titleColor(color: UIColor.white)
        bottomBtn.setBackgroundImage(UIImage.image(withColor: Theme.mainColor), for: .normal)
        bottomBtn.setBackgroundImage(UIImage.image(withColor: Theme.mainColorHighLightColor), for: .highlighted)
        bottomBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCMedium, size: 16)
        bottomBtn.layer.cornerRadius = 8
        bottomBtn.layer.masksToBounds = true
        bottomBtn.addTarget(self, action: #selector(bottomBtnAction), for: .touchUpInside)
        view.addSubview(bottomBtn)
        
        self.addSnpLayout()
        self.mvvmBind()
    }
    
    private func addSnpLayout(){
        titleLab.snp.makeConstraints { make in
            make.top.equalTo(NavBarHight + 60)
            make.centerX.equalTo(kScreenWidth/2)
        }
        
        oldPwdView.snp.makeConstraints { make in
            make.left.equalTo(30)
            make.right.equalTo(-30)
            make.top.equalTo(titleLab.snp.bottom).offset(68)
            make.height.greaterThanOrEqualTo(54)
        }
        
        password1View.snp.makeConstraints { make in
            make.left.equalTo(30)
            make.right.equalTo(-30)
            make.top.equalTo(oldPwdView.snp.bottom).offset(14)
            make.height.greaterThanOrEqualTo(54)
        }
        
        password2View.snp.makeConstraints { make in
            make.left.equalTo(30)
            make.right.equalTo(-30)
            make.top.equalTo(password1View.snp.bottom).offset(14)
            make.height.greaterThanOrEqualTo(54)
        }
        
        descLab.snp.makeConstraints { make in
            make.left.equalTo(30)
            make.right.equalTo(-30)
            make.top.equalTo(password2View.snp.bottom).offset(14)
            make.height.greaterThanOrEqualTo(22)
        }
        
        bottomBtn.snp.makeConstraints { make in
            make.left.equalTo(30)
            make.right.equalTo(-30)
            make.top.equalTo(descLab.snp.bottom).offset(80)
            make.height.equalTo(46)
        }
    }
    
    private func mvvmBind(){
        
        oldPwdView.textField.rx.controlEvent([.editingDidEnd, .editingDidEndOnExit]).subscribe {[weak self] _ in
            let password = self?.oldPwdView.textField.text ?? ""
            if password == "" {
                self?.oldPwdView.warnText = MMLocalizedString("update_input_old_password", comment: "请输入旧密码")
            } else if !XTManageCenter.isPassword(pasword: password) {
                self?.oldPwdView.warnText = MMLocalizedString("reset_pwd_rule", comment: "8~13位数字+字母组合")
            }else{
                self?.oldPwdView.warnText = ""
            }
        }.disposed(by: self.disBag)
        
        password1View.textField.rx.controlEvent([.editingDidEnd, .editingDidEndOnExit]).subscribe {[weak self] _ in
            let password1 = self?.password1View.textField.text ?? ""
            if password1 == "" {
                self?.password1View.warnText = MMLocalizedString("reset_pwd_input", comment: "请输入新密码")
            } else if !XTManageCenter.isPassword(pasword: password1) {
                self?.password1View.warnText = MMLocalizedString("reset_pwd_rule", comment: "8~13位数字+字母组合")
            }else{
                self?.password1View.warnText = ""
            }
        }.disposed(by: self.disBag)
        
        password2View.textField.rx.controlEvent([.editingDidEnd, .editingDidEndOnExit]).subscribe {[weak self] _ in
            let password2 = self?.password1View.textField.text ?? ""
            if password2 == "" {
                self?.password2View.warnText = MMLocalizedString("reset_pwd_input_again", comment: "请再次输入新密码")
            } else if !XTManageCenter.isPassword(pasword: password2) {
                self?.password2View.warnText = MMLocalizedString("reset_pwd_rule", comment: "8~13位数字+字母组合")
            }else{
                self?.password2View.warnText = ""
            }
        }.disposed(by: self.disBag)
        
        
        oldPwdView.textField.rx.controlEvent(.editingDidEndOnExit).subscribe {[weak self] _ in
            self?.oldPwdView.textField.resignFirstResponder()
        }.disposed(by: self.disBag)
        
        password1View.textField.rx.controlEvent(.editingDidEndOnExit).subscribe {[weak self] _ in
            self?.password1View.textField.resignFirstResponder()
        }.disposed(by: self.disBag)
        
        password2View.textField.rx.controlEvent(.editingDidEndOnExit).subscribe {[weak self] _ in
            self?.password2View.textField.resignFirstResponder()
        }.disposed(by: self.disBag)
    }
    
    ///校验data
    private func validateData() -> Bool{
        var flag = true
        let oldPassword = self.oldPwdView.textField.text ?? ""
        if oldPassword == "" {
            self.oldPwdView.warnText = MMLocalizedString("update_input_old_password", comment: "请输入旧密码")
            flag = false
        } else if !XTManageCenter.isPassword(pasword: oldPassword) {
            self.oldPwdView.warnText = MMLocalizedString("reset_pwd_rule", comment: "密码为8~13位数字+字母组合")
            flag = false
        }else {
            self.oldPwdView.warnText = ""
        }
        
        let password1 = self.password1View.textField.text ?? ""
        if password1 == "" {
            self.password1View.warnText = MMLocalizedString("reset_pwd_input", comment: "请输入新密码")
            flag = false
        } else if !XTManageCenter.isPassword(pasword: password1) {
            self.password1View.warnText = MMLocalizedString("reset_pwd_rule", comment: "密码为8~13位数字+字母组合")
            flag = false
        }else {
            self.password1View.warnText = ""
        }
        
        let password2 = self.password2View.textField.text ?? ""
        if password2 == "" {
            self.password2View.warnText = MMLocalizedString("reset_pwd_input_again", comment: "请再次输入新密码")
            flag = false
        }else if password2 != password1 {
            self.password2View.warnText = MMLocalizedString("reset_pwd_not_match", comment: "两次输入的密码不同")
            flag = false
        }else{
            self.password2View.warnText = ""
        }
        return flag
    }
    
    ///设置新密码
    @objc func bottomBtnAction(){
        let valid = self.validateData()
        if !valid {
            return
        }
        var param: [String: String] = [:]
        param["oldPassword"] = self.oldPwdView.textField.text ?? ""
        param["password"] = self.password1View.textField.text ?? ""
        self.view.showLoadingHUDText()
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.modifyPassword(param: param), objectType: CommondResModel.self) { data in
            self.view.handleLoading()
            let resultObj = data as? CommondResModel
            guard resultObj?.code == "1" else {
                self.view.makeToast(message: resultObj?.msg ?? "")
                return
            }
            self.view.makeToast(message: MMLocalizedString("update_pwd_success", comment: "修改成功"))
            self.perform(#selector(self.resetPwdSuccess), afterDelay: 1.5)
        } error: { err in
            self.view.handleLoading()
            self.view.makeToast(message: err?.domain ?? "")
        }
    }
    
    ///修改成功后退出登录
    @objc func resetPwdSuccess(){
        self.navigationController?.popToRootViewController(animated: false)
        if let tabbarVC = UIApplication.shared.keyWindow?.rootViewController as? BaseTabbarController {
            tabbarVC.selectedIndex = 0
        }
        XTManageCenter.shared.jumpToLoginView()
    }
}
